package glossos.search;

import java.util.Arrays;
import java.util.List;


/**
 * A decorator implementation of {@link Searcher} that caches common searches to improve performance.
 * For the moment, only pattern searches are cached. Everything else is simply delegated to the
 * decorated {@link Searcher}.
 * @author Otavio Macedo
 *
 */
public class CachedSearcher implements Searcher {
	private LRUCache<Integer, List<String>> patternCache;
	private Searcher searcher;

	public CachedSearcher(LRUCache<Integer, List<String>> patternCache, Searcher searcher) {
		this.patternCache = patternCache;
		this.searcher = searcher;
	}

	public Integer frequency(String sequence) {
		return searcher.frequency(sequence);
	}

	public String mostFrequentSequence(Integer size) {
		return searcher.mostFrequentSequence(size);
	}

	public List<String> sequencesMatching(String[] pattern) {
		Integer patternHashCode = Arrays.hashCode(pattern);
		if (!patternCache.contains(patternHashCode))
			patternCache.put(patternHashCode, searcher.sequencesMatching(pattern));
		return patternCache.get(patternHashCode);
	}

	public List<String> sequencesMatching(String pattern[], int start, int size) {
    	/* this method can be optimized. Instead of retrieving all results and cutting it down,
    	 * the traversal of the tree should stop when the size was reached.
    	 */
    	List<String> complete = sequencesMatching(pattern);
    	return complete.size() >= size
    		? complete.subList(start, start + size)
    		: complete;
	}

}
